package com.zsix.system.service.manager;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
import fr.opensagres.xdocreport.template.formatter.FieldsMetadata;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class WordTemplate {
    private static final Logger logger = LoggerFactory.getLogger(WordTemplate.class);
    public static void printDoc(String fileModelPath,String outfilePath, Map<String,Object> map, List<Map<Object,Object>> list) {
        InputStream ins = null;
        OutputStream out = null;
        try {
            //获取Word模板，模板存放路径
            ins = new FileInputStream(fileModelPath);
            //注册xdocreport实例并加载FreeMarker模板引擎
            IXDocReport report = XDocReportRegistry.getRegistry().loadReport(ins, TemplateEngineKind.Freemarker);
            //创建xdocreport上下文对象，用于存放具体数据
            IContext context = report.createContext();

            //创建要替换的文本变量
            Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> entry = iterator.next();
                context.put(entry.getKey(), entry.getValue());
            }
            if(list.size()>0){
                context.put("mapList", list);
                //创建字段元数据
                FieldsMetadata fm = report.createFieldsMetadata();
                //Word模板中的表格数据对应的集合类型
                fm.load("mapList", Map.class, true);
            }
            //输出到本地目录
            String filePath =outfilePath;
            File file=new File(filePath);
            if(!file.exists()){
                file.createNewFile();
            }
            out = new FileOutputStream(new File(filePath));
            report.process(context, out);
            String pdfPath=filePath.replace("docx","pdf");
            pdfPath=pdfPath.replace("doc","pdf");
            docToPDF(filePath,pdfPath);
        } catch (Exception e) {
            logger.info("生成word发生异常", e);
        } finally {
            try {
                if (ins != null){
                    ins.close();
                }
                if (out != null){
                    out.close();
                }
            } catch (IOException e) {
                logger.info("文件流关闭失败", e);
            }
        }
    }

    /**
     * 转化pdf
     * @param filePath
     * @param pdfPath
     */
    public static void docToPDF(String filePath,String pdfPath) {
        try {
            FileInputStream fileInputStream = new FileInputStream(filePath);
            XWPFDocument xwpfDocument = new XWPFDocument(fileInputStream);
            PdfOptions pdfOptions = PdfOptions.create();
            FileOutputStream fileOutputStream = new FileOutputStream(pdfPath);
            PdfConverter.getInstance().convert(xwpfDocument, fileOutputStream, pdfOptions);
            fileInputStream.close();
            fileOutputStream.close();
        }
        catch (IOException e){
            logger.info("转换PDF失败：", e);
        }
    }
}
